package config

import (
	"embed"
	"fmt"
	"gitee.com/snxamdf/wui/logs"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
)

var _efs embed.FS

func GetEFS() embed.FS {
	return _efs
}

func SetEmbed(efs embed.FS) {
	if efs == (embed.FS{}) {
		panic("设置 EFS is nil Error")
	}
	_efs = efs
	logs.Info("设置 go:embed")
}

func ReadFile(rootPath string) []string {
	var (
		result = make([]string, 0, 0)
		root   = fmt.Sprintf("%s/%s", AppResource, rootPath)
		err    error
	)
	if IsEnvDev() {
		err = filepath.Walk(root,
			func(path string, info os.FileInfo, err error) error {
				if err != nil {
					return err
				}
				if strings.Contains(path, ".") {
					result = append(result, path)
				}
				return nil
			})
	} else if IsEnvProd() {
		de, err := GetEFS().ReadDir(root)
		if err != nil {
			panic("编译读取静态资源错误" + err.Error())
		}
		readEfsDir(root, de, &result)
	}
	if err != nil {
		panic("编译读取静态资源错误" + err.Error())
	}
	logs.Info("读取文件目录:", root, "  文件个数:", len(result), "个")
	return result
}

func readEfsDir(root string, de []fs.DirEntry, result *[]string) {
	for _, dir := range de {
		if dir.IsDir() {
			var sonPath = fmt.Sprintf("%s/%s", root, dir.Name())
			de, err := GetEFS().ReadDir(sonPath)
			if err != nil {
				panic("编译读取静态资源错误" + err.Error())
			}
			readEfsDir(sonPath, de, result)
		} else {
			if strings.Contains(dir.Name(), ".") {
				var path = fmt.Sprintf("%s/%s", root, dir.Name())
				//logs.Info(path)
				*result = append(*result, path)
			}
		}
	}
}
